package com.lrd.snapshotorder.service.rule;

import com.lrd.snapshotorder.config.redis.RedissonClientService;
import com.lrd.snapshotorder.entity.RecipientAddress;
import com.lrd.snapshotorder.entity.SenderAddress;
import com.lrd.snapshotorder.entity.SnapshotOrder;
import com.lrd.snapshotorder.mapper.RecipientAddressMapper;
import com.lrd.snapshotorder.mapper.SenderAddressMapper;
import com.lrd.snapshotorder.mapper.SnapshotOrderMapper;
import com.lrd.snapshotorder.protocol.dto.order.OrderTaskCreateDto;
import com.lrd.snapshotorder.service.orderconsumer.OrderExecutorPool;
import com.lrd.snapshotorder.util.RandomCodeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 固定常量规则生成订单
 */
@Service
@Slf4j
public class NumericRule extends AbstractRule {

    @Autowired
    @Qualifier(value = "orderProducerThreadPool")
    private ThreadPoolExecutor orderProducerThreadPool;
    @Autowired
    private SnapshotOrderMapper snapshotOrderMapper;
    @Autowired
    private RecipientAddressMapper recipientAddressMapper;
    @Autowired
    private SenderAddressMapper senderAddressMapper;
    @Autowired
    private RedissonClientService redissonClientService;
    @Autowired
    private OrderExecutorPool orderExecutorPool;

    @Override
    public boolean verify(OrderTaskCreateDto orderTask) {
        return super.verify(orderTask);
    }

    @Override
    public Boolean createOrder(OrderTaskCreateDto orderTask) {
        //RBlockingDeque rBlockingDeque = redissonClientService.getRBlockingDeque(orderTask.getBatchNumber().toString());
        SenderAddress senderAddresses = senderAddressMapper.querySenderAddress();
        List<RecipientAddress> allAddress = recipientAddressMapper.getAllList();
        if (allAddress.size() >= orderTask.getBatchSize()) {
            for (int i = 0; i < orderTask.getBatchSize(); i++) {
                int index = i;
                orderProducerThreadPool.execute(() -> {
                    SnapshotOrder order = new SnapshotOrder();
                    String orderNo = orderTask.getBatchNumber() + RandomCodeGenerator.generateUniqueNumber();
                    order.setId(Long.parseLong(orderNo));
                    order.setOrderNo(orderNo + RandomCodeGenerator.generateUniqueStr());
                    order.setBatchNumber(orderTask.getBatchNumber());
                    order.setPostTime(orderTask.getPostTime());
                    order.setRecipient(allAddress.get(index).getRecipient());
                    order.setRecipientAddress(allAddress.get(index).getRecipientAddress());
                    order.setSender(senderAddresses.getSender());
                    order.setSenderAddress(senderAddresses.getSenderAddress());
                    order.setPostage(orderTask.getDefaultAmount());
                    order.setWeight(RandomCodeGenerator.getRangeRandomInteger(500, 1000));
                    //log.info("生成订单order={}", JSONUtil.toJsonStr(order));
                    snapshotOrderMapper.insert(order);
                    try {
                        //rBlockingDeque.put(order);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
            }
//            ThreadPoolExecutor threadPoolExecutor = orderExecutorPool.dynamicThreadPool(orderTask.getBatchNumber());
//            new OrderGeneratorConsumer2(threadPoolExecutor, snapshotOrderMapper, rBlockingDeque).execute();
        } else {
            int size = 0;
            for (int i = 0; i < allAddress.size(); i++) {
                if (size == orderTask.getBatchSize()) {
                    break;
                }
                if (allAddress.size() == i + 1) {
                    i = 0;
                }
                int index = i;
                orderProducerThreadPool.execute(() -> {
                    SnapshotOrder order = new SnapshotOrder();
                    String orderNo = orderTask.getBatchNumber() + RandomCodeGenerator.generateUniqueNumber();
                    order.setId(Long.parseLong(orderNo));
                    order.setOrderNo(orderNo + RandomCodeGenerator.generateUniqueStr());
                    order.setBatchNumber(orderTask.getBatchNumber());
                    order.setPostTime(orderTask.getPostTime());
                    order.setRecipient(allAddress.get(index).getRecipient());
                    order.setRecipientAddress(allAddress.get(index).getRecipientAddress());
                    order.setSender(senderAddresses.getSender());
                    order.setSenderAddress(senderAddresses.getSenderAddress());
                    order.setPostage(orderTask.getDefaultAmount());
                    order.setWeight(RandomCodeGenerator.getRangeRandomInteger(500, 1000));
                    //log.info("生成订单order={}", JSONUtil.toJsonStr(order));
                    snapshotOrderMapper.insert(order);
                    try {
                        //rBlockingDeque.put(order);
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                });
                size++;
            }
//            ThreadPoolExecutor threadPoolExecutor = orderExecutorPool.dynamicThreadPool(orderTask.getBatchNumber());
//            new OrderGeneratorConsumer2(threadPoolExecutor, snapshotOrderMapper, rBlockingDeque).execute();
        }
        return true;
    }
}
